package com.nuoyuan.wx.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


public class SmsUtil {
	
	private static final Logger log = LoggerFactory.getLogger(SmsUtil.class);
	
	private final static String USERID = "";
	private final static String ACCOUNT = "nctzhy";
	private final static String PASSWORD = "nctzhy001";
	
//	private final static String PREV_CONTENT = "【】";//TODO:短信内容签名
	
	public static final String DEF_CHATSET = "UTF-8";
	public static final int DEF_CONN_TIMEOUT = 50000;
    public static final int DEF_READ_TIMEOUT = 50000;

	
	public static boolean sendSms(String mobile, String content, String sendTime){
        String result = null;
        String url ="http://114.55.53.120/smsJson.aspx";//请求接口地址
        Map<String, Object> params = new HashMap<>();//请求参数
        params.put("userid", USERID);//接收短信的手机号码
        params.put("account", ACCOUNT);//短信模板ID，请参考个人中心短信模板设置
        params.put("password", getMd5Upper(PASSWORD));//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
        params.put("mobile", mobile);
        params.put("content", content);
        sendTime = Objects.isNull(sendTime) ? "" : sendTime;
        params.put("sendTime", sendTime);
        params.put("action", "send");
        params.put("extno", "");

        boolean sendRes = false;
        try {
            result =net(url, params, "POST");

            JSONObject object = JSON.parseObject(result);
            System.out.println(object.toString());
            if("Success".equals(object.getString("returnstatus"))){
                log.info("success result = " + result);
                sendRes = true;
            }else{
                log.info("error message = {}", object.get("message"));
                sendRes = false;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return sendRes;
    }
	
	public static String net(String strUrl, Map<String, Object> params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    log.error("sms net error = {}", e.getMessage());
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
	
	//将map型转为请求参数型
    public static String urlencode(Map<String,Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
	
	private static String getMd5Upper(String content) {
		return DigestUtils.md5Hex(content).toUpperCase();
	}
	
	
	public static void main(String[] args) {
//		System.out.println(DigestUtils.md5Hex("abc123").toUpperCase());
//		System.out.println(sendSms("15168452664", SmsTplCst.content));
	}
	
}
